/**
 * 旅游包车分析
 */

var vehicle;
var enterprise;
var iFrameName = this.name;
$(function(){
	RegionalStatistics.init();
});

var RegionalStatistics = {
	param: {},
	init: function(){
		var me = this;
		me.myChart=null;
		me.pieChart=null;
		me.initQueryTime();	
		me.initEmptyVehicleList();
		me.initVehicleUnitList();
		me.barChart = me.initBarChart();
		me.pieChart = me.initPieChart();
		var startTime=$("#inputStartDate").val();
	   	var endTime=$("#inputEndDate").val();
	   	me.queryBarChart();
		me.loadTableTitle();
		me.time=[];
		me.speed=[];
		me.initEvent();
	},

	initEvent: function(){
		var me = this;
		$("#exportExcel").click(function(){
			me.exportTable();
		});
		$("#chose").select2();
	},
	initBarChart: function(){
		var me = this;
		//计算显示的柱子数
		var percent = 100;

		option = {
		    color: ['#3398DB'],
		    legend: {
//                data:['业户统计']
            },
		    tooltip : {
		        trigger: 'axis',
		        show: true,
		        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
		        	show: false,
		            type : 'none'        // 默认为直线，可选为：'line' | 'shadow'
		        },
		        formatter:function(a){
		        	if(a[0].name==''){
		        		return;
		        	}
		        	var relVal = "";
		        	relVal = a[0].name+"："+a[0].value+"次";
		        	return relVal;
		        }
		    },
		    grid: {
		        left: '40px',
		        top:'40px',
		        right: '10px',
//		        containLabel: true
		    },
		    xAxis : [
		        {
		            type : 'category',
		            data : [],
		            axisTick: {
		                alignWithLabel: true
		            },
		            axisLabel:{
		            	textStyle: {
                        }
		            }
		        }
		    ],
		    yAxis : [
		        {
		            type : 'value',
		            show: true,    //显示纵轴false-不显示，true-显示
		            minInterval:1,
                    min:0,
                    axisLabel: {
                        formatter: function (value, index) {
                        	if (value >= 1 || value == 0) {
                            	if (value%1 === 0) {
                            		return value;
                            	}
                            }
                        }
                    },

		            name: '单位【次】',
		        }
		    ],
		    series : [
		        {
		            name:'业户统计',
		            type:'bar',		     
		            barMaxWidth: '60px',
		            data:[]
		        }
		    ],
		    dataZoom: [{
		        type: 'inside',
		        start: 0,
		        end: percent
		    }, {
		        start: 0,
		        end: percent,
		        fillerColor:'#A3E1A3',
		        handleColor:'#83A7D1',
		        showDetail:false
		    }]
		};
            var myChart = echarts.init(document.getElementById('barChart'));
            myChart.setOption(option);
            window.onresize = myChart.resize;
            myChart.on('click', function(param){
            	me.queryTable(param.name,null);
            	me.querypieChart(param.name,null);
            });
            
            return {
            	refash : function(option){
                    myChart.setOption(option);
            	},
            	option : option,
            	barChartDom : myChart
            };        
	},
	
	
	
	initPieChart: function(){
		var me = this;
		option = {
		    grid:{
		    	top:0,
		    	bottom:0,
		    	right:0,
		    },
		    tooltip : {
		        trigger: 'item',
		        formatter: "{a} <br/>{b} : {c} ({d}%)"
		    },
		    legend: {
		        orient: 'vertical',
		        left: 'left',
		        data: []
		    },
		    series : [
		        {
		            name: '异常统计',
		            type: 'pie',
		            radius: ['55%', '85%'],
		            center: ['50%', '50%'],
		            avoidLabelOverlap: true,
		            label: {
		                normal: {
		                    show: true,
		                    formatter: '{b}',
		                    backgroundColor: '#eee',
		                    borderColor: '#aaa',
		                    borderWidth: 1,
		                    borderRadius: 4,
		                },
		                emphasis: {
		                    show: true,
		                    position:'inside',
		                    textStyle: {
		                        fontSize: '15',
		                        fontWeight: 'bold'
		                    }
		                }
		            },
		            labelLine: {
		                normal: {
		                    show: true,
		                },
		                
		            },
		            data:[]
		        }
		    ],
			 color: ['rgb(249,124,37)','rgb(74,178,191)','rgb(134,218,179)','rgb(97,160,168)']
		};
		 var PieChart = echarts.init(document.getElementById('pieChart'));
		 PieChart.setOption(option);
         window.onresize = PieChart.resize;
         return {
         	refash : function(option){
         		PieChart.setOption(option);
         	},
         	option : option,
         	pieChartDom : PieChart
         };
	},
initVehicleUnitList:function(){
	$('#selectVehicleUnitSel').select2({
		theme: "default",
	        allowClear: true,
	        placeholder: "全部车辆",
	        ajax:{
	            url:appCtx + "base/report/RegionalStatistics/getAuthCar.html",
	            dataType:"json",
	            delay:250,
	           async : true,
	            data:function(params){
	                return {
	                    name: params.term,
	                    page: params.page || 1
	                };
	            },
	            cache:true,
	            processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部车辆"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.id, "text":obj.vehicle_no};
 	                    options.push(option);
	    				});
 	                return {
 	                	results: options,
 	                    pagination: {
 	                        more:false
 	                    }
 	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
	})
		/*var me = this;
		$.ajax({
			type : 'post',
			url : appCtx + "base/report/RegionalStatistics/getAuthCar.html",
			cache : false,
			dataType : "JSON",
			success : function(data) {
				var selectStr="<option value=''>请选择车辆</option>";
				$.each(data,function(index,f){
					selectStr+="<option value='"+f.vehicle_no+"_"+f.vehicle_color+"'>"+f.vehicle_no+"</option>";
				});
				$('#selectVehicleUnitSel').html(selectStr);		
				$("#selectVehicleUnitSel").select2();
				$("#selectVehicleUnitSel").change(function(){
				vehicle = $(this).children('option:selected').val(); 
			});
		}
	});*/
},

initEmptyVehicleList: function(){
	$('#selectVehicleSel').select2({
		theme: "default",
	        allowClear: true,
	        placeholder: "全部业户",
	        ajax:{
	            url:appCtx + "base/report/RegionalStatistics/getQueryEnterAndPlatByRole.html",
	            dataType:"json",
	            delay:250,
	           async : true,
	            data:function(params){
	                return {
	                    name: params.term,
	                    page: params.page || 1
	                };
	            },
	            cache:true,
	            processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部业户"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.entId, "text":obj.entName};
 	                    options.push(option);
	    				});
 	                return {
 	                	results: options,
 	                    pagination: {
 	                        more:false
 	                    }
 	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
	})
	/*var me = this;
	$.ajax({
		type : 'post',
		url : appCtx + "base/report/RegionalStatistics/getQueryEnterAndPlatByRole.html",
		cache : false,
		dataType : "JSON",
		success : function(data) {
				var selectStry="<option value=''>业户查询</option>";
				$.each(data,function(index,f){
					selectStry+="<option value='"+f.entName+"'>"+f.entName+"</option>";
				});
				$('#selectVehicleSel').html(selectStry);		
				$("#selectVehicleSel").select2();
				$("#selectVehicleSel").change(function(){
					enterprise = $(this).children('option:selected').val();
				});
			}
	});*/

},
queryBarChart:function(){
	var  chose = $("#chose").val();
	var vehicle = null;
	var enterprise = null;
	if(chose==0){ //车辆
		vehicle = $.trim($("#selectVehicleUnitSel").val());
	}else if(chose==1){	//业户	
		enterprise = $.trim($("#selectVehicleSel").val());
	}
	var me = this;
	var startTime=$("#inputStartDate").val();
	var endTime=$("#inputEndDate").val();
   	var end_str = (endTime).replace(/-/g,"/");//一般得到的时间的格式都是：yyyy-MM-dd hh24:mi:ss，所以我就用了这个做例子，是/的格式，就不用replace了。  
	var end_date = new Date(end_str);//将字符串转化为时间  
	//开始时间  
	var sta_str = (startTime).replace(/-/g,"/");  
	var sta_date = new Date(sta_str); 
	var num = (end_date-sta_date)/(1000*3600*24);//求出两个时间的时间差，这个是天数  
	var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了） 
	if(days>30){
		global.ajaxLoading.pop("查询时间不能超过30天",false,2000);
		return;
	}
	$.ajax({
		type : 'post',
		url : appCtx+"base/report/RegionalStatistics/getbarchart.html",
		data:{
			vehicle_no:vehicle,
			enterprise:enterprise,
			startTime:startTime,
			endTime:endTime
		},
		cache : false,
		dataType : "JSON",
		success : function(data) {
			if(vehicle==null||vehicle==''||vehicle==undefined){
				var option = me.barChart.option;
				option.xAxis[0].data =data.xAxisData; //['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
				option.series[0].data =data.series;// [10, 52, 200, 334, 390, 330, 220];
				me.barChart.refash(option);
				me.vehicleIdList = data.vehicleIdList;
				//默认展示第一个的列表
				if(enterprise==null||enterprise==''){
					me.queryTable(data.vehicleIdList[0],null);
					me.querypieChart(data.vehicleIdList[0],null);
				}else{
					me.queryTable(enterprise,null);
					me.querypieChart(enterprise,null);
				}
			}else if(vehicle!=null){
				var option = me.barChart.option;
				option.xAxis[0].data =data.xAxisData; //['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
				option.series[0].data =data.series;// [10, 52, 200, 334, 390, 330, 220];
				me.barChart.refash(option);
				me.vehicleIdList = data.vehicleIdList;
				me.queryTable(null,vehicle);
				me.querypieChart(null,vehicle);
			}
		},
	});
},
/**
 * @Description: 用户单击条形图的某一条,获取条形图的业户ID查询业户异常车辆列表方法
 * @param vehicleId
 * @param plateNumber
 */
queryTable: function(enterprise_name,vehicleId){
	var startTime=$("#inputStartDate").val();
	var endTime=$("#inputEndDate").val();
	// 查询参数
	var params = [{
		name : 'startTime',
		value : startTime
	},{
		name : 'endTime',
		value : endTime
	},{
		name : 'enterprise_name',
		value : enterprise_name
	},{
		name : 'vehicleId',
		value : vehicleId
	}];
	$("#objTable").flexOptions({
		url : appCtx + "base/report/RegionalStatistics/getTables.html",
		newp : 1,// 设置起始页
		params : params
	// 设置查询参数
	}).flexReload();// 重新加载
},
	
/**
 * @Description: 用户单击条形图的某一条,获取条形图的业户ID查询业户异常车辆列表方法
 * @param vehicleId
 * @param plateNumber
 */
querypieChart:function(enterprise_name,vehicleId){
	var me = this;
	var startTime=$("#inputStartDate").val();
	var endTime=$("#inputEndDate").val();
	$.ajax({
		url:appCtx+"base/report/RegionalStatistics/getpieChart.html?time="+new Date().getTime(),
		type:"post",
		cache : false,
		data:{
			enterprise_name:enterprise_name,
			vehicleId:vehicleId,
			startTime:startTime,
			endTime:endTime,
		},
		dataType:"text",
		success:function(data){
			$("#noData").remove();
			var data = eval('(' + data + ')');
			var option = me.pieChart.option;
			if(data.list.length==0){
				global.noData("#pieChart");	
			}else{
				var arr = new Array();
				$.each(data.list,function(index,vo){
					vo.index=index+1;
					arr.push(vo);
				});
    			var maps=data.map;
    			
				var names = new Array();
    			var datas =new Array();
				for(var key in maps){
					var mapdata=new Object();;
					 mapdata.value=maps[key];
					 names.push(key);
					 mapdata.name=key;
					 datas.push(mapdata);
				}
				option.legend.data=names;
				option.series[0].data=datas;// [10, 52, 200, 334, 390, 330, 220];
				me.pieChart.refash(option);
			}
		}
	});
},
    getColumn:function(){
    	return [{
            display : '区域名称',
            name : 'area_name',
            width : 27,
            sortable : false,
            align : 'left',
            showTitle : 'area_name'
        },{
            display : '车牌号',
            name : 'vehicle_no',
            width : 15,
            sortable : false,
            align : 'left',
            showTitle : 'vehicle_no'
        },{
            display : '颜色',
            name : 'vehicle_color',
            width : 8,
            sortable : false,
            align : 'left',
            paramcolnames:["vehicle_color"],
            handlefunction:function(vehicle_color){
            	var str='无数据';
            	if(vehicle_color=='1'){
            		str='蓝色';
            	}else if(vehicle_color=='2'){
            		str='黄色';
            	}else if(vehicle_color=='3'){
            		str='黑色';
            	}else if(vehicle_color=='4'){
            		str='白色';
            	}else if(vehicle_color=='9'){
            		str='其他';
            	}
        		return str;
            }
        },{
            display : '驶入区域时间',
            name : 'enter_time',
            width : 22,
            sortable : false,
            align : 'left',
            paramcolnames:["enter_time"],
            handlefunction:function(enter_time){
        		return global.getTime(new Date(Number(enter_time)));
            }
        },{
            display : '驶出区域时间',
            name : 'leave_time',
            width : 22,
            sortable : false,
            align : 'left',
            paramcolnames:["leave_time"],
            handlefunction:function(leave_time){
        		return global.getTime(new Date(Number(leave_time)));
            }
        },{
        	display : '操作',
            name : 'Handler',
            width : 6,
            sortable : false,
            align : 'center',
            paramcolnames:['vehicle_no','enter_time','leave_time','vehicle_color'],
            handlefunction:function(vehicleId,enter_time,leave_time,vehicleColor){
            	var handleStr = "";	
            	enter_time=global.getTime(new Date(Number(enter_time)));
            	leave_time=global.getTime(new Date(Number(leave_time)));
        		handleStr += '<div   onclick="getlaln(\''+vehicleId+'\',\''+enter_time+'\',\''+leave_time+'\',\''+vehicleColor+'\')"  style="padding:0px;float:left;width:35px;height:19px;cursor:pointer;"><img  src="'+global.url.domain+'gps-web/resources/images/track.png" title="轨迹回放"></div>';
        		return handleStr;
            }
        }]
    },
    loadTableTitle:function(){
    	$("#objTable").flexigrid({
	            dataType : 'json',
	            colModel :this.getColumn() ,
	            usepager : true,// 是否分页，默认为true。
	            singleSelect:true,
				sortname : "id",// 第一次加载数据时排序列
				sortorder : "desc",// 第一次加载数据时排序类型
	            height:308,
				useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
				rp : 10,// 每页记录数，默认为10
	            widthType:'%',
	            width:$('.detail-report').width(),
	         });	 
    },
    exportTable:function(){
		var options = $("#objTable").getOptions();
		//总记录数
		var total = options.total;
		if(total==0){
			global.ajaxLoading.pop("无数据",false,1000);
			return;
		}
		var pages = options.pages;
		//设置默认的开始结束页
		$("#StartPageIndex").val(1);
		$("#EndPageIndex").val(pages);
        $("#exportTitle").html("旅游车进出重点区域分析导出");
    	$("#exportModal").modal('show');
    },

    exportExcel : function(){
    	var me = this;
    	$("#exportModal").modal('hide');
		var header1 = JSON.stringify(me.getColumn());
		var header2 = JSON.parse(header1);
		var  chose = $("#chose").val();
		var vehicle = null;
		var enterprise = null;
		if(chose==0){ //车辆
			vehicle = $("#selectVehicleUnitSel").val();
		}else if(chose==1){	//业户	
			enterprise = $("#selectVehicleSel").val();
		}
		//开始页数
		var StartPage=$("#StartPageIndex").val();
		//结束页数
		var EndPage=$("#EndPageIndex").val();
		var options = $("#objTable").getOptions();
		//总记录数
		var total = options.total;
		var pagesize = options.rp;
		var headerWidth = $('.detail-report').width();
		for(var i=0;i<header2.length;i++){
			header2[i].width = Math.ceil(headerWidth / 100 * header2[i].width);
		}
		header2.splice(header2.length-1,1);
		var header3 = JSON.stringify(header2);
		 var imageUrl = me.barChart.barChartDom.getDataURL({
			type: 'png',
		    pixelRatio: 1
		}); 
		 
		 var imageUrl2 = me.pieChart.pieChartDom.getDataURL({
				type: 'png',
			    pixelRatio: 1
		}); 
		 
		//表头
		var colModelList=new Array();
		colModelList.push(header3);
		var colModel= $.toJSON(colModelList);
		
		//图片
		var imgsrcList=new Array();
		imgsrcList.push(imageUrl);
		imgsrcList.push(imageUrl2);
		var imgsrc= $.toJSON(imgsrcList);
			
		var param =  {
				startTime:$("#inputStartDate").val()+" 00:00；00",
				endTime: $("#inputEndDate").val()+" 23:59:59",
				vehicleId:vehicle,
				enterprise_name:enterprise,
				colModel:colModel,
				StartPage:StartPage,
				EndPage:EndPage,
				pagesize:pagesize,
				title:"旅游车进出重点区域分析导出",
				imgsrc:imgsrc
		};
		post(appCtx+"base/report/RegionalStatistics/exportRegionalStatistics.html",param);
		
	},
    initQueryTime:function(){
        var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        	
        var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString(),dd1 = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.length == 1) {
	        dd = '0' + dd;
	    }
	    if (dd1.length == 1) {
	        dd1 = '0' + (Number(dd1)+1);
	    }
        $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
        $("#inputEndDate").val(yyyy + '-' + mm + '-' +dd1);
      },
            
      
	initMap: function(carPic,lineArr,vehicle_no,vehicle_color,address){
		var map = new AMap.Map("mymap", {
	        resizeEnable: true,
	        center: lineArr[0],
	        zoom: 14
	    });
	    startMarker = new AMap.Marker({
	        map: map,
	        position: lineArr[0],
	        icon: global.url.domain + "gps-web/resources/images/mapTool/start.png",
	        offset: new AMap.Pixel(-15, -30)
	    });
	    var content ='车牌：'+vehicle_no+'</br>车牌色：'+vehicle_color;//+ '</br>地点: '+address;
	    var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
	    infoWindow.setContent(content);
	    infoWindow.open(map, startMarker.getPosition());
	    endMarker = new AMap.Marker({
	        map: map,
	        position: lineArr[lineArr.length-1],
	        icon: global.url.domain + "gps-web/resources/images/mapTool/end.png",
	        offset: new AMap.Pixel(-15, -30)
	    });
	    // 绘制轨迹
	    var polyline = new AMap.Polyline({
	        map: map,
	        path: lineArr,
	        strokeColor: "#00A",  //线颜色
	        strokeWeight: 3,      //线宽
	    });
	    var passedPolyline = new AMap.Polyline({
	        map: map,
	        strokeColor: "#F00",  //线颜色
	        strokeWeight: 3,      //线宽
	    });
	},

};

var base64 = new Base64();
function getlaln(vehicleId,enter_time,leave_time,vehicleColor){
	var address;
	var me = this;
/*	startDateTime ='2017-09-01 00:00:00';
	endDateTime = '2017-09-12 15:26:27';*/
	var vehicle_no_color = vehicleId+'_'+vehicleColor;/*'贵AT1920'+"_2";*/
	vehicle_no_color = base64.encode(vehicle_no_color);
	var str
	if(vehicleColor=='1'){
		str='蓝色';
	}else if(vehicleColor=='2'){
		str='黄色';
	}else if(vehicleColor=='3'){
		str='黑色';
	}else if(vehicleColor=='4'){
		str='白色';
	}else if(vehicleColor=='9'){
		str='其他';
	}
	var lng;
	var lat;
		$.ajax({
		type : 'post',
		url : appCtx+'gis/playback/queryTrackList.html',
		cache : false,
		dataType : "json",
		data:{
			  vehicle_no_color:vehicle_no_color,
			  start_time:enter_time,
			  end_time:leave_time,
			},
		success : function(rdata) {
			console.log(rdata);
			if(rdata){
				var data = rdata.rows;
				var lnglatArr = new Array();
				for(var i=0;i<data.length;i++){
					lng = data[i].longitudeD;
					lat = data[i].latitudeD;
					var lnglat = new Array();
					console.log("lng:"+lng+','+"lat:"+lat);
    				lnglat.push(lng);
    				lnglat.push(lat);
    				getaddr(lng,lat);
    				lnglatArr.push(lnglat);
				}
				var carPic = appCtx + "resources/images/mapTool/car0.png";//TODO 无法获取车辆类型，暂时先取0
				RegionalStatistics.initMap(carPic,lnglatArr,vehicleId,str,addr);
			
			}
		}
	});
}

function chose(){
	var  chose = $("#chose").val();
	if(chose==0){ //车辆
		$("#chosecar").attr("style","background: #1d63a9;")
		$("#choseenterpirse").attr("style","background: #dfdfdf");
		$("#vehicleSelDiv").hide();	
		$("#UnitSel").show();
	}
	if(chose==1){	//业户	
		$("#choseenterpirse").attr("style","background: #1d63a9;")
		$("#chosecar").attr("style","background: #dfdfdf");
		$("#UnitSel").hide();
		$("#vehicleSelDiv").show();
	}
};

var addr="无地点记录";
function getaddr(longitude,latitude){
   $.ajax({
     url : "http://58.67.161.51:18192/?location="+longitude+","+latitude,
     dataType : 'jsonp',
     async:false, 
     success : function(data){
           var ac = data.regeocodes[0].addressComponent;
           addr=data.regeocodes[0].formatted_address;
          }
    });
}